const defaultData = require('./data');

function getDialogCtx(ref) {
	var selector = ref.selector,
		pageCtx = ref.pageCtx;

	var ctx = pageCtx;
	if (!ctx) {
		var pages = getCurrentPages();
		ctx = pages[pages.length - 1];
	}
	console.log(ctx)
	return ctx.$vm.$refs[selector];
}

function getParsedOptions() {
	let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

	return Object.assign({
		// 自定义 btn 列表
		// { type: 按钮类型，回调时以此作为区分依据，text: 按钮文案, color: 按钮文字颜色 }
		buttons: []
	}, defaultData, options);
}

function Dialog(options, pageCtx) {
	const parsedOptions = getParsedOptions(options);
	let dialogCtx = getDialogCtx({
		selector: parsedOptions.selector,
		pageCtx: pageCtx
	});

	if (!dialogCtx) {
		console.error('无法找到对应的dialog组件，请于页面中注册并在 wxml 中声明 dialog 自定义组件');
		return Promise.reject({
			type: 'component error'
		});
	}

	const parsedOptionsButton = parsedOptions.buttons;
	const buttons = parsedOptionsButton === undefined ? [] : parsedOptionsButton;
	let showCustomBtns = false;
	if (buttons.length === 0) {
		if (parsedOptions.showConfirmButton) {
			buttons.push({
				type: 'confirm',
				text: parsedOptions.confirmButtonText,
				color: parsedOptions.confirmButtonColor
			});
		}

		if (parsedOptions.showCancelButton) {
			var cancelButton = {
				type: 'cancel',
				text: parsedOptions.cancelButtonText,
				color: parsedOptions.cancelButtonColor
			};
			if (parsedOptions.buttonsShowVertical) {
				buttons.push(cancelButton);
			} else {
				buttons.unshift(cancelButton);
			}
		}
	} else {
		showCustomBtns = true;
	}
	return new Promise((resolve, reject) => {
		const optionsData = Object.assign({}, parsedOptions, {
			buttons: buttons,
			showCustomBtns: showCustomBtns,
			key: '' + new Date().getTime(),
			show: true,
			promiseFunc: {
				resolve: resolve,
				reject: reject
			},
			openTypePromiseFunc: null
		})
		for (let key in optionsData) {
			dialogCtx[key] = optionsData[key];
		}
	});

}
Dialog.close = (options, pageCtx) => {
	var parsedOptions = getParsedOptions(options);

	var dialogCtx = getDialogCtx({
		selector: parsedOptions.selector,
		pageCtx: pageCtx
	});

	if (!dialogCtx) {
		return;
	}
	dialogCtx.show = false;
	dialogCtx.promiseFunc = null;
	dialogCtx.openTypePromiseFunc = null;
};

module.exports = Dialog;
